package com.zzx.boot.controller;

import com.zzx.boot.entity.User;
import com.zzx.boot.entity.dto.LoginDto;
import com.zzx.boot.entity.vo.UserInfoVo;
import com.zzx.boot.service.UserService;
import com.zzx.boot.utils.R;
import com.zzx.boot.utils.SecurityContext;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.Objects;

@RestController
@RequestMapping("/user")
@RequiredArgsConstructor
public class UserController {

    private final UserService userService;
    private final SecurityContext securityContext;

    @PostMapping("/login")
    public R login(@RequestBody LoginDto loginDto){
        return R.success(userService.getUserByUsernameAndPassword(loginDto.getUsername(), loginDto.getPassword()));
    }

    @GetMapping("/info/{id}")
    public R getUserInfo(@PathVariable("id")Long id){
        return R.success(userService.getUserInfoByUserId(id));
    }

    @GetMapping("/{username}")
    public R getUserInfoByPhoneOrWeixinNumber(@PathVariable("username") String username){
        return R.success(userService.getUserByUsername(username));
    }

    @GetMapping("/info")
    public R<UserInfoVo> getUserInfo(){
        UserInfoVo userInfo = securityContext.getUserInfo();
        if(Objects.isNull(userInfo)){
            throw new RuntimeException("用户凭证过期了");
        }
        return R.success(userInfo);
    }

}
